package com.lin.ovc.pomodoro.config;

//import com.lin.ovc.pomodoro.filter.TokenAuthFilter;

import com.lin.ovc.pomodoro.filter.JwtAuthenticationFilter;
import com.lin.ovc.pomodoro.filter.TokenAuthFilter;
import com.lin.ovc.pomodoro.filter.TokenLoginFilter;
import com.lin.ovc.pomodoro.security.CustomAuthenticationSuccessHandler;
import com.lin.ovc.pomodoro.security.TokenLogoutHandler;
import com.lin.ovc.pomodoro.security.UnauthEntryPoint;
import com.lin.ovc.pomodoro.security.UserAuthService;
import com.lin.ovc.pomodoro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(0)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 自动装配自定义认证服务LoginService
    @Autowired
    UserAuthService userAuthService;

    @Autowired
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    UserService userService;

    // 注入 PasswordEncoder 类到 spring 容器中
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userAuthService).passwordEncoder(passwordEncoder());
    }

    //    @Bean
//    public CorsConfigurationSource corsConfigurationSource() {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration configuration = new CorsConfiguration();
//        configuration.setAllowCredentials(true);
//        configuration.setAllowedOrigins(Collections.singletonList("*"));
//        configuration.setAllowedMethods(Collections.singletonList("*"));
//        configuration.setAllowedHeaders(Collections.singletonList("*"));
//        configuration.setMaxAge(Duration.ofHours(1));
//        source.registerCorsConfiguration("/**", configuration);
//        return source;
//    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        //支持跨域访问
        http.cors()
                .configurationSource(corsConfigurationSource());

        http.authorizeRequests()
                .antMatchers("/layui/**", "/index", "/login.html") //表示配置请求路径
                .permitAll() // 指定 URL 无需保护。
                .anyRequest() // 其他请求
                .authenticated(); //需要认证

        http.formLogin() // 表单登录
                .loginPage("/login.html")
                .loginProcessingUrl("/user/login")
                .successHandler(customAuthenticationSuccessHandler)
//                .defaultSuccessUrl("/index.html").permitAll()
                .failureForwardUrl("/error.html").permitAll();

//        http.exceptionHandling().authenticationEntryPoint(new UnauthEntryPoint());

        http.logout().logoutUrl("/user/logout")//退出路径
                .addLogoutHandler(new TokenLogoutHandler());
        http.addFilterBefore(new JwtAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class).httpBasic();
//        http.addFilter(new TokenLoginFilter(authenticationManager(),userService)).httpBasic();
//                .addFilter(new TokenAuthFilter(authenticationManager())).httpBasic();
    }
}
